package com.edu.cdp.utils;

import java.time.Duration;
import java.util.HashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class CodeUtils {
    public final HashMap<String, String> emailsCodeMap = new HashMap<String, String>(16);
    public final Duration codeExpiryDuration = Duration.ofMinutes(1);

    /**
     * 保存调用接口得到的验证码
     *
     * @param email 用户邮箱
     * @param code  用户获取到的验证码
     */
    public void saveCode(String email, String code) {
        emailsCodeMap.put(email, code);
        System.out.println("保存的验证码：" + emailsCodeMap.get(email));
        //定时删除过期的验证码
        Runnable removalTask = () -> emailsCodeMap.remove(email);
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.schedule(removalTask, codeExpiryDuration.toMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 比较用户的输入的验证码与接口得到的验证码
     *
     * @param email 用户邮箱
     * @param code  验证码输入的验证码
     * @return
     */
    public int contrastCode(String email, String code) {
        System.out.println(emailsCodeMap);
        String storeCode = emailsCodeMap.get(email);
        System.out.println("获取到的验证码：" + storeCode);

        if (storeCode == null) {
            //验证码失效
            return 0;
        }

        if (storeCode.equals(code)) {
            //验证成功删除验证码
            emailsCodeMap.remove(email);
            return 1;
        } else {
            //验证错误
            return -1;
        }
    }

    public static void main(String[] args) {
        CodeUtils codeUtils = new CodeUtils();

        codeUtils.saveCode("123456@qq.com", "123456");
        codeUtils.contrastCode("123456@qq.com", "12345644");
    }
}